package com.nus.fellowmark.common.mongo.controller;

import com.nus.fellowmark.common.mongo.service.MongoFileService;
import com.nus.fellowmark.common.mongo.model.LoadFile;
import com.nus.fellowmark.common.response.ResponseEnum;
import com.nus.fellowmark.common.response.ServerResponseEntity;
import com.nus.fellowmark.common.utils.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * @author Ruoyi Chen
 * @email chenruoyisz@gmail.com
 * @create 2023/2/17
 */
@RestController
public class FileController {

    @Autowired
    MongoFileService mongoFileService;

    @PostMapping("/upload")
    public ServerResponseEntity upload(@RequestParam("file") MultipartFile file) {
        return ServerResponseEntity.success(mongoFileService.uploadFile(file));
    }

    @PostMapping("/uploadWithName")
    public ServerResponseEntity uploadWithName(@RequestParam("file") MultipartFile file, @RequestParam("name") String name) {
        mongoFileService.uploadFileWithName(file, name);
        return ServerResponseEntity.success(mongoFileService.uploadFile(file));
    }

    @GetMapping("/download/{id}")
    public ServerResponseEntity download(@PathVariable String id, ServletOutputStream outputStream, HttpServletResponse response) {
        LoadFile loadFile = mongoFileService.downloadFile(id);
        if (loadFile == null) {
            return ServerResponseEntity.fail(ResponseEnum.NO_SUCH_FILE);
        }

        // if want to view the file in the browser, comment this line; else to download the file, uncomment this.
//        response.setHeader("Content-Disposition", "attachment;filename="+loadFile.getFilename());
        response.setContentType("application/pdf;charset=UTF-8");

        InputStream in = loadFile.getInputStream();
        BufferedOutputStream out = new BufferedOutputStream(outputStream);
        Boolean outputFile = FileUtils.outputFile(out, in);
        if (!outputFile) {
            return ServerResponseEntity.fail(ResponseEnum.FAIL_TO_OUTPUT_FILE);
        }

        return ServerResponseEntity.success();
    }



    @GetMapping("/delete/{id}")
    public ServerResponseEntity delete(@PathVariable String id) {
        Boolean deleteFile = mongoFileService.deleteFile(id);
        if (deleteFile) {
            return ServerResponseEntity.success();
        }
        return ServerResponseEntity.showFailMsg("fail");
    }

    @GetMapping("/downloadZipFile")
    public ServerResponseEntity downloadAsZip(@RequestBody List<String> ids, HttpServletResponse response) throws IOException {
        mongoFileService.downloadFilesAsZip(ids, response);
        return ServerResponseEntity.success();
    }
}
